﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bonobo.Irc.Client
{
    // FIXME: make internal
    public struct IrcResponse
    {
        private const char Space = ' ';
        private const char Colon = ':';

        private String _command;
        private IrcResponseType _type;
        private readonly String _prefix;
        private readonly String[] _arguments;


        public IrcResponse(IrcResponseType type, params String[] arguments)
        {
            _type = type;
            _arguments = arguments;
            _command = String.Empty;
            _prefix = String.Empty;
            CreateCommand();
        }

        public IrcResponse(String prefix, IrcResponseType type, params String[] arguments)
        {
            _prefix = prefix;
            _type = type;
            _arguments = arguments;
            _command = String.Empty;
            CreateCommand();
        }



        public IrcResponseType Type
        {
            get { return _type; }
        }

        public IList<String> Arguments
        {
            get { return _arguments; }
        }

        public String Prefix
        {
            get { return _prefix; }
        }

        public String Message
        {
            get { return GetMessageWithoutPrefix(_prefix, _command); }
        }



        public override string ToString()
        {
            return _command;
        }



        private void HandleSpaces()
        {
            for (int i = 0; i < _arguments.Length; i++)
            {
                if (_arguments[i].Contains(Space))
                {
                    _arguments[i] = Colon + _arguments[i];
                }
            }
        }

        private void CreateCommand()
        {
            HandleSpaces();

            if (String.IsNullOrEmpty(_prefix))
            {
                _command = ((int)_type).ToString();
            }
            else
            {
                _command =  Colon + _prefix + ((int)_type).ToString();
            }

            // FIXME: use StringBuilder
            foreach (var item in _arguments)
            {
                _command += ' ' + item;
            }
        }


        public static bool IsLoginError(IrcResponseType type)
        {
            switch(type)
            {
                case IrcResponseType.ErrorErrorneusNickname:
                case IrcResponseType.ErrorNicknameCollision:
                case IrcResponseType.ErrorNicknameInUse:
                case IrcResponseType.ErrorNoNicknameGiven:
                    return true;

                default:
                    return false;
            }            
        }

        // FIXME: again, refactor this into some kind of hashtable mapping response types to 
        //        functions parsing them
        public static bool TryParse(String message, out IrcResponse output)
        {
            var factory = new IrcResponseFactory();

            String prefix = GetMessagePrefix(message);
            String msgWithoutPrefix = GetMessageWithoutPrefix(prefix, message);

            String strType = GetMessageType(msgWithoutPrefix);
            int type;
            if (Int32.TryParse(strType, out type))
            {
                String msgArguments = GetMessageArguments(msgWithoutPrefix, strType);
                String[] arguments = ParseArguments(msgArguments);

                if (type == (int)IrcResponseType.ErrorNotRegistred)
                {
                    if (!String.IsNullOrEmpty(arguments[0]) && !String.IsNullOrEmpty(arguments[1]))
                    {
                        output = factory.NotRegistred(prefix, arguments[0], arguments[1]);
                        return true;
                    }
                    else if (!String.IsNullOrEmpty(arguments[0]))
                    {
                        output = factory.NotRegistred(prefix, arguments[0]);
                        return true;
                    }
                }
                else if (type == (int)IrcResponseType.ErrorAlreadyRegistred)
                {
                    if (!String.IsNullOrEmpty(arguments[1]))
                    {
                        output = factory.AlreadyRegistred(prefix, arguments[1]);
                        return true;
                    }
                }
                else if (type == (int)IrcResponseType.ErrorNeedMoreParams)
                {
                    if (!String.IsNullOrEmpty(arguments[0]) && !String.IsNullOrEmpty(arguments[1]))
                    {
                        output = factory.NeedMoreParams(prefix, arguments[0], arguments[1]);
                        return true;
                    }
                }
                else if (type == (int)IrcResponseType.ErrorNoNicknameGiven)
                {
                    if (!String.IsNullOrEmpty(arguments[0]))
                    {
                        output = factory.NoNickNameGiven(prefix, arguments[0]);
                        return true;
                    }
                }
                else if (type == (int)IrcResponseType.ErrorErrorneusNickname)
                {
                    if (!String.IsNullOrEmpty(arguments[0]) && !String.IsNullOrEmpty(arguments[1]))
                    {
                        output = factory.ErrorneusNickname(prefix, arguments[0], arguments[1]);
                        return true;
                    }
                }
                else if (type == (int)IrcResponseType.ErrorNicknameInUse)
                {
                    if (!String.IsNullOrEmpty(arguments[0]) && !String.IsNullOrEmpty(arguments[1]))
                    {
                        output = factory.NicknameInUse(prefix, arguments[0], arguments[1]);
                        return true;
                    }
                }
                else if (type == (int)IrcResponseType.ErrorNicknameCollision)
                {
                    if (!String.IsNullOrEmpty(arguments[0]) && !String.IsNullOrEmpty(arguments[1]))
                    {
                        output = factory.NicknameCollision(prefix, arguments[0], arguments[1]);
                        return true;
                    }
                }
                else
                {
                    output = new IrcResponse(prefix, IrcResponseType.UnknownResponse, arguments);
                    return true;
                }
            }

            output = new IrcResponse();
            return false;
        }

        private static string GetMessageArguments(String messageWithoutPrefix, String command)
        {
            if (messageWithoutPrefix.Length < command.Length + 1)
            {
                return String.Empty;
            }
            messageWithoutPrefix = messageWithoutPrefix.Remove(0, command.Length + 1);
            if (messageWithoutPrefix[0] == ' ')
            {
                messageWithoutPrefix = messageWithoutPrefix.Remove(0, 1);
            }
            return messageWithoutPrefix;
        }

        private static string GetMessageWithoutPrefix(String prefix, String message)
        {
            if (String.IsNullOrEmpty(prefix))
            {
                if (message.StartsWith(": "))
                {
                    message.Substring(2);
                }
                return message;
            }
            else
            {
                return message.Remove(0, prefix.Length + 1);
            }
        }

        private static String[] ParseArguments(String arguments)
        {
            var list = new List<String>();
            var arr = arguments.ToCharArray();

            var temp = String.Empty;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == ':' && i + 1 < arr.Length)
                {
                    list.Add(arguments.Substring(i + 1));
                    break;
                }
                else
                {
                    if (arr[i] != ' ')
                    {
                        temp += arr[i];
                    }
                    else
                    {
                        list.Add(temp);
                        temp = String.Empty;
                    }

                }
            }

            return list.ToArray();
        }

        private static String GetMessageType(String msgWithoutPrefix)
        {
            return msgWithoutPrefix.Substring(0, msgWithoutPrefix.IndexOf(' '));
        }

        private static String GetMessagePrefix(string message)
        {
            if (message.StartsWith(":"))
            {
                return message.Substring(1, message.IndexOf(' '));
            }

            return String.Empty;
        }

    }
}
